package com.example.transaction_springboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.transaction_springboot.entity.Admin;
import com.example.transaction_springboot.mapper.AdminMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static AdminMapper staticAdminMapper;

    @Resource
    AdminMapper adminMapper;

    public void setUserService() {
        staticAdminMapper = adminMapper;
    }

    //生成token
    public static String createToken(String userId, String sign) {
        return JWT.create().withAudience(userId)  //将user id 保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) //2小时候token过期
                .sign(Algorithm.HMAC256(sign)); //以password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static Admin getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticAdminMapper.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
